package com.powernode.usermgt.controller;

import com.powernode.usermgt.bean.User;
import com.powernode.usermgt.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.List;

/**
 * @Author: 曾铖坚
 * @Date: 2024/10/4 17:49
 * @Version: 1.0.0
 */
@Controller
public class UserController {
    @Autowired
    private UserDao userDao;

    @RequestMapping(value = "/user", method = RequestMethod.GET)
    public String list(Model model) {
        // 从数据库中查询用户信息
        List<User> users = userDao.selectALL();
        // 将用户信息存放到request域中
        model.addAttribute("users",users);
        // 转发
        return "user_list";
    }

    @RequestMapping(value = "/user",method = RequestMethod.POST)
    public String save(User user){
        // 调用userDao保存用户数据
        userDao.insert(user);
        // 重定向到用户列表（让浏览器重新发送一次全新的请求，去请求列表页面）
        return "redirect:/user";
    }

    @RequestMapping(value = "/user/{id}",method = RequestMethod.GET)
    public String toEdit(@PathVariable("id") Long id,Model model){
        // 根据id查找用户对象
        User user = userDao.selectById(id);
        // 将用户对象存储到request域中
        model.addAttribute("user",user);
        return "user_edit";
    }

    @RequestMapping(value = "/user",method = RequestMethod.PUT)
    public String edit(User user){
        // 调用userDao修改用户数据
        userDao.update(user);
        // 重定向到用户列表（让浏览器重新发送一次全新的请求，去请求列表页面）
        return "redirect:/user";
    }

    @RequestMapping(value = "/user/{id}",method = RequestMethod.DELETE)
    public String delete(@PathVariable("id") Long id){
        // 根据id删除用户信息
        userDao.deleteById(id);
        // 重定向到列表页面
        return "redirect:/user";
    }
}
